package com.maodou.android.ui.page.account

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.R
import com.maodou.android.ui.page.Verify2faKey
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.AppLoadingOverlay
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.utils.Logger

/**
 * @Author Xing
 * @CreateTime 2025年09月22日
 * @Description 获取账号2fa验证码
 */
@Composable
fun Verify2faScreen(
    key: Verify2faKey,
    viewModel: AccountViewModel = hiltViewModel(),
) {
    val context = LocalContext.current
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    LaunchedEffect(key.account) {
        key.account?.let { viewModel.getTwoFaCode(it) }
    }

    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(lifecycleOwner) {

        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> {
                    viewModel.setV2FAResume(true)
                }

                Lifecycle.Event.ON_RESUME -> {
                    Logger.d("恢复===============")
                }

                Lifecycle.Event.ON_PAUSE -> {
                    viewModel.setV2FAResume(false)
                }

                Lifecycle.Event.ON_STOP -> {
                    viewModel.clearTableData()
                }

                Lifecycle.Event.ON_DESTROY -> {
                }

                else -> {}
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            viewModel.clearTableData()
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        ActionBar(
            title = "2FA验证码",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = {
                Navigator3.pop()
            },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        if(uiState.authCode.isNotEmpty()) Column(
            modifier = Modifier.padding(12.dp)
        ) {

            AppText(
                text = "2FA秘钥",
                style = MaterialTheme.typography.titleSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(elevation = 1.dp, shape = RoundedCornerShape(12.dp))
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color.White)
                    .padding(horizontal = 12.dp, vertical = 16.dp)
                    .debouncedClickable { copyText(context, "${key.account?.twoFa}") },
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                AppText(
                    text = "${key.account?.twoFa}",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontSize = 17.sp
                    ),
                    color = Color.Black
                )
            }

            VSpacer(20.dp)

            AppText(
                text = "验证码",
                style = MaterialTheme.typography.titleSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Row (
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(elevation = 1.dp, shape = RoundedCornerShape(12.dp))
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color.White)
                    .padding(horizontal = 12.dp, vertical = 12.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {

                Column(
                    modifier = Modifier.debouncedClickable {
                        copyText(context, uiState.authCode)
                    }
                ) {
                    AppText(
                        text = uiState.authCode,
                        style = MaterialTheme.typography.titleLarge,
                        color = if(uiState.secondsLeft < 8) Color(0xffd81e06) else MaterialTheme.colorScheme.primary,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )

                    AppText(
                        text = "验证码(点击复制)",
                        style = MaterialTheme.typography.titleSmall.copy(
                            fontSize = 12.sp
                        ),
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }

                TotpCountdown(
                    progress = uiState.progress,
                    secondsLeft = uiState.secondsLeft,
                    onClickRefresh = {  }
                )

            }
            VSpacer(10.dp)
            Text(
                text = "注：验证码是通过技术匹配到的验证码",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

        }


    }

}

@Composable
private fun TotpCountdown(
    progress: Float,
    secondsLeft: Int,
    onClickRefresh: () -> Unit,
) {
    Box(
        modifier = Modifier
            .size(56.dp)
            .clip(CircleShape)
            .debouncedClickable { onClickRefresh() },
        contentAlignment = Alignment.Center
    ) {
        val arcColor = if(secondsLeft < 8) Color(0xffd81e06) else MaterialTheme.colorScheme.primary
        Canvas(modifier = Modifier.matchParentSize()) {
            val sweep = 360f * progress.coerceIn(0f, 1f)
            drawArc(
                color = arcColor,
                startAngle = -90f, // 从 12 点方向开始
                sweepAngle = sweep,
                useCenter = true,
                size = size
            )
        }
        AppText(
            text = secondsLeft.coerceAtLeast(0).toString(),
            style = MaterialTheme.typography.labelLarge.copy(
                textAlign = TextAlign.Center
            ),
            color = Color.White,
            modifier = Modifier
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.0f))
                .padding(0.dp),
        )
    }
}